﻿using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    [RequireComponent(typeof(Image))]
    public class RedDot : MonoBehaviour
    {
        public string parentKey;
        public string key;

        private Image img;
        private Text text;

        private void Awake()
        {
            if (key == "")
            {
                Debug.LogError($"{name}的RedDot.key不能为空");
                return;
            }
            RedDotHelper.Register(key, parentKey, this);
            SetNumber(RedDotHelper.GetNumberWithChildren(key));
        }

        public void SetKey(string parentKey, string key)
        {
            this.parentKey = parentKey;
            this.key = key;
            RedDotHelper.Register(key, parentKey, this);
            SetNumber(RedDotHelper.GetNumberWithChildren(key));
        }

        public void SetNumber(int number)
        {
            img ??= GetComponent<Image>();
            img.enabled = number > 0;
            if (!text)
            {
                text = GetComponentInChildren<Text>();
            }
            if (text)
            {
                text.enabled = img.enabled;
                text.text = number.ToString();
            }
        }
    }
}